package cn.darkfire.CarWeb.Dao.Impl;

import cn.darkfire.CarWeb.Dao.CarDao;
import cn.darkfire.CarWeb.POJO.Car;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;


@Repository("carDao")
public class CarDaoImpl implements CarDao {

    @Autowired //注入template
    private JdbcTemplate template;

    @Override
    public int insert(Car obj) {
        String sql = "insert into cars values (?,?,?,?)";
        try {
            return template.update(sql,obj.getCarID(),obj.getCarName(),obj.getCarType(),obj.getCarPrice());
        }catch (Exception e){
            return 0;
        }
    }

    @Override
    public int del(String id) {
        String sql = "delete from cars where carID = ?";
        return template.update(sql,id);
    }

    @Override
    public Car select(String name) {
       return null;
    }

    @Override
    public int update(Car obj) {
        String sql = "update cars set carName = ?,carType = ?,carPrice = ? where carID = ?";
        return template.update(sql,obj.getCarName(),obj.getCarType(),obj.getCarPrice(), obj.getCarID());
    }

    @Override
    public List<Car> selectAllCar() {
        String sql = "select * from cars";
        return template.query(sql,new BeanPropertyRowMapper<Car>(Car.class));
    }

    @Override
    public List<Car> searchCar(String name) {
        String sql = "select * from cars where carName like ?";
        List<Car> car = template.query(sql,new BeanPropertyRowMapper<Car>(Car.class),"%"+name+"%");
        return car;
    }

    @Override
    public int getID() {
        String sql = "select carID from cars order by carID+'0' desc LIMIT 0,1";
        return template.queryForObject(sql,Integer.class);
    }


}
